package com.project.forlearningdemo.config;

import com.project.forlearningdemo.dao.UserMapper;
import com.project.forlearningdemo.pojo.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserMapper userMapper;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 这里用户默认使用用户权限
        return new SimpleAuthorizationInfo();
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

        User user1 = userMapper.queryUser(null, null, token.getUsername());
        User user2 = null;
        if(user1 == null){
            user2 = userMapper.queryUser(null, token.getUsername(), null);
            if(user2 == null) {
                return null; //代表账号不存在
            }
        }
        User user = user1!=null?user1:user2;
        if(!user.getPassword().equals(String.valueOf(token.getPassword()))){
            throw new IncorrectCredentialsException(); //代表密码错误
        }
        return new SimpleAuthenticationInfo(user, user.getPassword(), "");
    }
}
